package com.itheima.mp.timer;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

@Slf4j
public class TimerDemo {
    public static void main(String[] args)  throws Exception {
//        timerAtDate();
        timerOfDelayAndPeriod();
    }

    @Test
    private static void timerOfDelayAndPeriod() throws InterruptedException {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Timer timer = new Timer();

        TimerTask timerTaskAtPointedDate = new TimerTask() {
            @Override
            public void run() {
                log.info("timerOfDelayAndPeriod timertask " + LocalDateTime.now().format(dtf));
            }
        };
        timer.schedule(timerTaskAtPointedDate, 0, TimeUnit.SECONDS.toMillis(2));

        TimeUnit.SECONDS.sleep(10);
        System.out.println("cancel timer task ..............");
        timer.cancel();

    }


    private static void timerAtDate() {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        Timer timer = new Timer();
        LocalDateTime now = LocalDateTime.now();
        System.out.println("now datetime==>> " + now.format(dtf));
        now = now.plusMinutes(1);
        TimerTask timerTaskAtPointedDate = new TimerTask() {
            @Override
            public void run() {
                log.info("timerTaskAtPointedDate timertask " + LocalDateTime.now().format(dtf));
            }
        };
        ZoneId zoneId = ZoneId.systemDefault();
        ZonedDateTime zdt = now.atZone(zoneId);
        Date date = Date.from(zdt.toInstant());
        timer.schedule(timerTaskAtPointedDate, date);
    }
}
